var path = require("path");
var express = require('express');
var template = require('art-template');

var platform_deployer,config,server,platform_dai,logger;

module.exports = function(opts){
    config = opts.config;
    server = opts.server;
    logger = opts.logger;

    platform_dai = require("./platform-dai")({
        db_prefix : config.db_prefix,
        db_uri : config.db_uri,
        logger : logger,
        server : server
    });

    platform_deployer = require('./platform-deployer')(config);

    return {
        load:load_app
    }
}

/*
  绑定主页
*/
function platform_homepage(app_module){
    var tpl_dir = path.resolve(config.root_dir,app_module.platform_root,app_module.app_name,"index.html");

    server.get("/platform/"+app_module.app_name,function(req,res){

        var html = platform_deployer.compile(tpl_dir,app_module);

        //var html = template(tpl_dir, data);

        res.header("Content-Type","text/html");
        res.end(html);
    });
}

/*
  设置静态文件目录
*/
function platform_dev_static(app_module){
    (app_module.config.dev_static || []).forEach(function(static_dir){        
        var url_path = path.join("/",app_module.platform_root,app_module.app_name,static_dir);
        url_path = url_path.replace(/\\/g,"/");
        //console.log(url_path);
        server.use(url_path,express.static(path.join(config.root_dir,url_path)));
    });
}


var dataCache = require("./platform-datacache");
function platform_data_cache(app_module){
    app_module.dataCache = dataCache;
}




/*
  load app
*/
function load_app(platform_name,root_dir){
    logger.info("loading platform "+platform_name);  

    var app_root = path.join(config.root_dir, config.platform_root,platform_name);
    var app_config = require(path.join(app_root,"config.json"));

    var platform_module = {
        app_name:platform_name,
        config:app_config
    }

    platform_module.platform_root = config.platform_root;


    //数据访问接口

    if(app_config.usedai){
        platform_dai(platform_module);
        var app_dai = require(path.join(app_root,"dai"));
        app_dai(platform_module);
    }
    //

    //app主页
    platform_homepage(platform_module);

    //静态资源（开发模式）
    platform_dev_static(platform_module);
    

    /*
    //动态部署（开发模式）
    platform_deployer(platform_module);
    */

    //添加数据缓存
    platform_data_cache(platform_module);

   

    /*
    if(platform_module.onReady){
        platform_module.onReady();
    }*/

    return platform_module;
}